package com.security.security.config;

import com.security.security.filter.SmsAuthenticationFilter;
import com.security.security.handler.CustomAuthenticationHandler;
import com.security.security.provider.SmsAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @作者: 林江
 * @创建时间: 2024/1/3
 * @功能:
 */
public class SmsSecurityConfigurerAdapter
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private UserDetailsService userDetailsService;

    public SmsSecurityConfigurerAdapter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        CustomAuthenticationHandler customAuthenticationHandler = new CustomAuthenticationHandler();
        smsAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationHandler);
        smsAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationHandler);
        // 认证提供器
        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
        smsAuthenticationProvider.setUserDetailsService(userDetailsService);

        //将自定义的过滤器交由spring管理
        smsAuthenticationFilter = postProcess(smsAuthenticationFilter);

        // ③ 将短信认证过滤器放到密码认证之前
        http.authenticationProvider(smsAuthenticationProvider)
                .addFilterAfter(
                        smsAuthenticationFilter,
                        UsernamePasswordAuthenticationFilter.class
                );
    }
}
